/*
 * @Author: liuhandong
 * @Date: 2020-9-23 11:18:10
 */
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;

public class ARScene
{
    private ARManager mParent;
    private GameObject mRoot;
    private ARSessionOrigin mOrigin;
    private ARPlaneManager mPlaneMan;
    private ARRaycastManager mRaycastMan;
    private ARFaceManager mFaceMan;

    public ARScene(ARManager parent, GameObject rootPrefab = null)
    {
        mParent = parent;
        if(rootPrefab == null)
        {
            mRoot = new GameObject("ARScene");
        }
        else
        {
            mRoot = (GameObject.Instantiate(rootPrefab) as GameObject);
        }
        mOrigin = mRoot.GetComponent<ARSessionOrigin>();
        if(mOrigin == null)
        {
            mOrigin = mRoot.AddComponent<ARSessionOrigin>();
        }
    }

    public GameObject GetRoot()
    {
        return mRoot;
    }

    public void Dispose()
    {
        if(mRoot != null)
        {
            GameObject.Destroy(mRoot);
            mFaceMan = null;
            mPlaneMan = null;
            mRaycastMan = null;
            mOrigin = null;
            mRoot = null;
        }
    }

    public ARRaycastManager GetRaycastMan()
    {
        _EnsureRaycastMan();
        return mRaycastMan;
    }

    public ARFaceManager GetFaceManager()
    {
        _EnsureFaceMan();
        return mFaceMan;
    }

    private void _EnsurePlaneMan()
    {
        if(mPlaneMan == null)
        {
            mPlaneMan = mRoot.gameObject.GetComponent<ARPlaneManager>();
            if(mPlaneMan == null)
            {
                mPlaneMan = mRoot.gameObject.AddComponent<ARPlaneManager>();
            }
        }
    }

    private void _EnsureRaycastMan()
    {
        if(mRaycastMan == null)
        {
            mRaycastMan = mRoot.gameObject.GetComponent<ARRaycastManager>();
            if(mRaycastMan == null)
            {
                mRaycastMan = mRoot.gameObject.AddComponent<ARRaycastManager>();
            }
        }
    }

    private void _EnsureFaceMan()
    {
        if(mFaceMan == null)
        {
            mFaceMan = mRoot.gameObject.AddComponent<ARFaceManager>();
            var face = mFaceMan.TryGetFace(default(TrackableId));
        }
    }
}